package com.whisperarts.financer.app.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import com.whisperarts.financer.app.Application;
import com.whisperarts.financer.app.dialogs.AddTransactionDialog;
import com.whisperarts.financer.app.dialogs.SelectAccountDialog;
import com.whisperarts.financer.app.utils.UIUtils;
import com.whisperarts.financer.app.views.NavigatorView;
import com.whisperarts.financer.dao.AccountsDAO;
import com.whisperarts.financer.model.account.Account;
import com.whisperarts.financer.model.transaction.Transaction;

public class AddTransactionAction extends Action implements 
	ISelectionListener, IWorkbenchAction {
	
	private final IWorkbenchWindow window;
	public final static String ID = "com.whisperarts.financer.app.actions.addTransaction";
	private IStructuredSelection selection;
	
	
	public AddTransactionAction(IWorkbenchWindow window) {
		this.window = window;
		setId(ID);
		setText("&New transaction");
		setToolTipText("Add new transaction");
		setImageDescriptor(AbstractUIPlugin.imageDescriptorFromPlugin(Application.PLUGIN_ID, ISharedImages.IMG_OBJ_ADD));
		window.getSelectionService().addSelectionListener(this);
		setEnabled(true);
	}
	
	@Override
	public void selectionChanged(IWorkbenchPart part, ISelection incoming) {
		if (part.getSite().getId().equals(NavigatorView.ID))
			selection = (IStructuredSelection) incoming;
	}
	
	@Override
	public void dispose() {
		window.getSelectionService().removeSelectionListener(this);
	}
	
	@Override
	public void run() {
		Account account = null;
		if (! (selection.size() == 1 && selection.getFirstElement() instanceof Account)) {
			SelectAccountDialog dialog = new SelectAccountDialog(window);
			if (dialog.open() != Window.OK)
				return;
			else ;
				account = dialog.getAccount();
		} else {
			account = (Account)selection.getFirstElement();
		}
		
		AddTransactionDialog dialog = new AddTransactionDialog(window.getShell(), account);
		if (dialog.open() == Window.OK) {
			Transaction tx = dialog.getTransaction();
			if (AccountsDAO.saveTransaction(tx) == 0) {
				Account txAccount = AccountsDAO.getAccountById(tx.getAccountId());
				if (txAccount != null) {
					txAccount.getTransactions().add(tx);
				}
				UIUtils.updateActiveEditor(window, txAccount);
			}
		}
	}
}
